{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "import os\n",
    "# 根据自己项目的位置设置工作路径\n",
    "os.chdir('..\\\\..\\\\..\\\\..\\\\..\\\\JAVA\\\\chinese-medicine-identification\\\\image-cnn-model\\\\')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "import keras\n",
    "from keras.callbacks import ReduceLROnPlateau, EarlyStopping\n",
    "'''\n",
    "模型的训练\n",
    "'''\n",
    "\n",
    "img_size = (299, 299)\n",
    "dataset_dir = '..\\\\..\\\\..\\\\datasets\\\\dataset'\n",
    "img_save_to_dir = 'resources\\\\image-traing\\\\'\n",
    "log_dir = 'resources\\\\train-log'\n",
    "\n",
    "model_dir = 'resources\\\\keras-model\\\\'\n",
    "\n",
    "train_datagen = keras.preprocessing.image.ImageDataGenerator(\n",
    "    rescale=1. / 255,\n",
    "    shear_range=0.2,\n",
    "    width_shift_range=0.4,\n",
    "    height_shift_range=0.4,\n",
    "    rotation_range=90,\n",
    "    zoom_range=0.7,\n",
    "    horizontal_flip=True,\n",
    "    vertical_flip=True,\n",
    "    preprocessing_function=keras.applications.xception.preprocess_input)\n",
    "\n",
    "test_datagen = keras.preprocessing.image.ImageDataGenerator(\n",
    "        rescale=1. / 255,\n",
    "    preprocessing_function=keras.applications.xception.preprocess_input)\n",
    "\n",
    "train_generator = train_datagen.flow_from_directory(\n",
    "    dataset_dir,\n",
    "    save_to_dir=img_save_to_dir,\n",
    "    target_size=img_size,\n",
    "    class_mode='categorical')\n",
    "\n",
    "validation_generator = test_datagen.flow_from_directory(\n",
    "    dataset_dir,\n",
    "    save_to_dir=img_save_to_dir,\n",
    "    target_size=img_size,\n",
    "    class_mode='categorical')\n",
    "\n",
    "early_stop = EarlyStopping(monitor='val_loss', patience=15)\n",
    "reduce_lr = ReduceLROnPlateau(monitor='val_loss', patience=7, mode='auto', factor=0.2)\n",
    "\n",
    "\n",
    "def medicine_name_label_to_file():\n",
    "    with open(model_dir + 'medicine_name-lable.csv', 'w', encoding='utf8') as f:\n",
    "        for k, v in validation_generator.class_indices.items():\n",
    "            f.write(k + ',' + str(v) + '\\n')\n",
    "\n",
    "\n",
    "tensorboard = keras.callbacks.tensorboard_v2.TensorBoard(log_dir=log_dir)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "img_size = (299, 299, 3)\n",
    "base_model = keras.applications \\\n",
    "    .xception.Xception(include_top=False,\n",
    "                       weights='../../resources/keras-model/'\n",
    "                               'xception_weights_tf_dim_ordering_tf_kernels_notop.h5',\n",
    "                       input_shape=img_size,\n",
    "                       pooling='avg')\n",
    "model = keras.layers.Dense(628, activation='softmax', name='predictions')(base_model.output)\n",
    "model = keras.Model(base_model.input, model)\n",
    "for layer in base_model.layers:\n",
    "    layer.trainable = False\n",
    "\n",
    "model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\n",
    "\n",
    "history = model.fit_generator(train_generator,\n",
    "                              steps_per_epoch=train_generator.samples // train_generator.batch_size,\n",
    "                              epochs=100,\n",
    "                              validation_data=validation_generator,\n",
    "                              validation_steps=validation_generator.samples // validation_generator.batch_size,\n",
    "                              callbacks=[early_stop, reduce_lr, tensorboard])\n",
    "model.save(model_dir + 'chinese_medicine_model_v1.0.h5')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}